﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Net;
using System.IO;

namespace FSV.SaveHtml
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		private void SaveButton_Click(object sender, EventArgs e)
		{
			Uri url = new Uri(UrlInput.Text.Trim());
			string path = Application.StartupPath + "\\OutPut\\";
			//validate input data
			if (Directory.Exists(path + FolderNameInput.Text.Trim()))
			{
				WriteLog("Project name already exist");
				return;
			}
			path=path + FolderNameInput.Text.Trim();
			//create target folder
			Directory.CreateDirectory(path);
			path += "\\";
			//Create base folder
			Directory.CreateDirectory(path + "css");
			Directory.CreateDirectory(path + "js");
			Directory.CreateDirectory(path + "images");
			Directory.CreateDirectory(path + "images\\content");

			var s = Load(url.ToString());
			//save url content
			SaveContent(path+"index.html", s);
			//read content from stream
			StreamReader sr = new StreamReader(s);
			string content = sr.ReadToEnd();
			//use third party to parse HTML
			HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
			doc.LoadHtml(content);
			//parse url to save releated data
			//css save to css folder
			foreach (var item in doc.DocumentNode.SelectNodes("//link[@type='text/css']"))
			{

			}
			//js to js folder
			//image bg or image in css file move to images folder
			//other image use img tag move to images/content
		}

		void SaveContent(string path,string url)
		{
			var s = Load(url);

			SaveContent(path, s);
		}

		void SaveContent(string path, Stream stream)
		{
			using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
			{
				stream.CopyTo(fs);
				fs.Flush();
			}
		}

		Stream Load(string url)
		{
			WebRequest rq = WebRequest.Create(url);
			var rp = rq.GetResponse();
			return rp.GetResponseStream();
		}

		void WriteLog(string msg, params string[] args)
		{

		}
	}
}
